package com.mk.config;

import com.mk.client.MyMQTTClient;
import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Data
public class MqttConfiguration {

    private static final Logger log = LoggerFactory.getLogger(MqttConfiguration.class);
    @Value("${mqtt.host}")
    String host;
    @Value("${mqtt.username}")
    String username;
    @Value("${mqtt.password}")
    String password;
    @Value("${mqtt.clientId}")
    String clientId;
    @Value("${mqtt.timeout}")
    int timeOut;
    @Value("${mqtt.keepalive}")
    int keepAlive;
    @Value("${mqtt.topic1}")
    public String topic1;
    @Value("${mqtt.topic2}")
    public String topic2;

    @Bean//注入spring
    public MyMQTTClient myMQTTClient() throws MqttException {
        // 如果以 mqtt:// 开头，就换成 tcp://
        String serverUri = host.startsWith("mqtt://")
                ? host.replaceFirst("^mqtt://", "tcp://")
                : host;

        // 用替换后的地址去构建客户端
        MyMQTTClient rawClient = new MyMQTTClient(serverUri,username,password, clientId,timeOut,keepAlive);
        //（其他选项：用户名、密码、超时、心跳等）
        rawClient.connect();

        return rawClient;
    }
}
